import axios from 'axios'
import { message } from 'ant-design-vue'
import { useUserStore } from '@/stores/user'

// 创建 Axios 实例
const myAxios = axios.create({
  baseURL: 'http://119.91.227.162:8190',
  timeout: 60000,
  withCredentials: true,
})

// 请求拦截器
myAxios.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers.Authorization = userStore.token
    }
    console.log('【请求头】', config.headers)
    return config
  },
  (error) => Promise.reject(error),
)
// 响应拦截器（保持你原来的逻辑）
myAxios.interceptors.response.use(
  (response) => {
    const { data } = response
    if (data.code === 500) {
      if (
        !response.request.responseURL.includes('user/get/login') &&
        !window.location.pathname.includes('/user/login')
      ) {
        message.warning('请先登录')
        window.location.href = `/user/login?redirect=${window.location.href}`
      }
    }
    return response
  },
  (error) => Promise.reject(error),
)

export default myAxios
